import React, {useCallback, useEffect, useState} from "react"
import {
    getMarketDetail, MarketDetail,
} from "../../apis/MarketsApi";
import {Descriptions, Divider, Table, theme} from "antd";
import DataPageLayout from "../../components/DataPageLayout";
import dashboardPageStore from "../../store/DashboardPageStore";
import {observerDashboardPageWrapper} from "./ObserverDashboardPageWrapper";
import {useNavigate} from "react-router";
import LazyTabs from "../../components/LazyTabs";
import {Pageable} from "../../utils/Page";
import {
    exportMarketsGoodsToExcel,
    getMarketGoodsBrands,
    getMarketGoodsCategories,
    getMarketGoodsFactories,
    queryMarketsGoods,
    QueryMarketsGoodsResponse
} from "../../apis/MarketsGoodsApi";
import OnlinePaginationGoodsTable, {QueryGoodsTableDataCondition} from "../../components/OnlinePaginationGoodsTable";
import {mergePaginationAndPageable, useTableFilterDateRangeColumnProps} from "../../utils/AntdTableUtils";
import ArrayUtils from "@zxy-cn/array-utils";
import {
    createMarketOrder, deleteMarketOrder,
    getMarketOrderCreatedEmployeeByMarketId,
    MarketOrderStatus,
    marketOrderStatuses,
    marketOrderStatusMap,
    QueryMarketOrderResponse, queryMarketOrders
} from "../../apis/MarketOrderApi";
import {LocalDate, OffsetDateTime} from "@js-joda/core";
import {NumberIdAndName} from "../../types/BasicModels";
import {saveTo} from "../../utils/FileSaver";
import LoadableButton from "../../components/LoadableButton";
import employeeAuthorizationStore from "../../store/EmployeeAuthorizationStore";
import {DeleteOutlined} from "@ant-design/icons";
import {
    getCheckInventoryRecordCreatedEmployeesByMarketId,
    QueryMarketCheckInventoryRecordResponse,
    queryMarketCheckInventoryRecords
} from "../../apis/MarketCheckInventoryRecordApi";
import {useGlobalStyle} from "../../global.style";
import {Link} from "react-router-dom";
import MarketAccountTabPage from "./MarketAccountTabPage";
import {DATE_WITH_TIME_FORMATER, YEAR_MONTH_DAY_FORMATER} from "../../utils/Date";
import MarketStatisticTabPanel from "./MarketStatisticTabPanel";
import MarketShoppingGuidesTabPage from "./MarketShoppingGuidesTabPage";
import MarketSalaryTabPanel from "./MarketSalaryTabPanel";
import MarketInternalGoodsCodeManager from "../MarketInternalCodeManager";
import MarketSettlementTabPanel from "./MarketSettlementTabPanel";


export interface pageProps {
    id: number
}

const myPath = "markets/{id}"

const MarketDetailPage: React.FC<pageProps> = ({id}) => {
    const [loading, setLoading] = useState(false)
    const [data, setData] = useState<MarketDetail>()
    const query = useCallback(() => {
        setLoading(true)
        getMarketDetail(id).then(response => {
            dashboardPageStore.setTitle(myPath.replace("{id}", id.toString()), response.data.name)
            setData(response.data)
        }).finally(() => {
            setLoading(false)
        })
    }, [id])

    useEffect(() => {
        query()
    }, [query]);

    let token = theme.useToken();

    let navigate = useNavigate();

    return (
        <>
            {!loading ? <Descriptions title={"卖场信息"}>
                <Descriptions.Item label={"名称"}>{data?.name}</Descriptions.Item>
                {data?.saleManager == null ? null :
                    <Descriptions.Item label={"业务员"}>{data?.saleManager?.name}</Descriptions.Item>}
                {data?.shoppingGuides.length ?? 0 > 0 ? <Descriptions.Item
                    label={"导购"}>{data?.shoppingGuides?.map(it => it.name)?.join("，")}</Descriptions.Item> : null}
                {data?.excludeBrands.length ?? 0 > 0 ? <Descriptions.Item
                    label={"排除品牌"}>{data?.excludeBrands?.map(it => it.name)?.join("，")}</Descriptions.Item> : null}
                <Descriptions.Item label={"商品数量"}>{data?.goodsAmount}</Descriptions.Item>
                <Descriptions.Item label={"订单数量"}>{data?.orderAmount}</Descriptions.Item>
            </Descriptions> : null}

            {employeeAuthorizationStore.hasAnyAuthority("卖场_盘点_查询", "卖场_订单_查询", "卖场_盘点_查询") &&
                <LazyTabs lazyItems={[
                    employeeAuthorizationStore.hasAuthority("卖场_盘点_查询") ? {
                        label: "商品",
                        key: "goods",
                        render: () => <MarketGoodsTabPage id={id} name={data?.name}/>
                    } : null,
                    employeeAuthorizationStore.hasAuthority("卖场_订单_查询") ? {
                        label: "订单",
                        key: "orders",
                        render: () => <MarketOrdersTabPage id={id}/>
                    } : null,
                    employeeAuthorizationStore.hasAuthority("卖场_盘点_查询") ? {
                        label: "盘点",
                        key: "inventory",
                        render: () => <MarketInventoryTabPage id={id}/>
                    } : null,
                    employeeAuthorizationStore.hasAuthority("卖场_户头_查询") ? {
                        label: "户头",
                        key: "account",
                        render: () => <MarketAccountTabPage id={id}/>
                    } : null,
                    employeeAuthorizationStore.hasAuthority("卖场_结算_查询") ? {
                        label: "结算",
                        key: "settlement",
                        render: () => <MarketSettlementTabPanel id={id}/>
                    } : null,
                    employeeAuthorizationStore.hasAllAuthority("卖场_户头_查询", "卖场_订单_查询") ? {
                        label: "统计",
                        key: "statistic",
                        render: () => <MarketStatisticTabPanel id={id}/>
                    } : null,
                    employeeAuthorizationStore.hasAnyAuthority("卖场_导购_薪水_方案_查询",) ? {
                        label: "薪资",
                        key: "salary",
                        render: () => <MarketSalaryTabPanel id={id}/>
                    } : null,
                ].filter(it => !!it).map(it => it!!)} defaultActiveKey={"goods"}/>}

        </>
    )
}

export default observerDashboardPageWrapper(MarketDetailPage, myPath, "卖场详情")

const MarketGoodsTabPage: React.FC<{ id: number, name?: string }> = ({id, name}) => {
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryMarketsGoodsResponse[]>([])
    const [totalElements, setTotalElements] = useState(0)
    const [condition, setCondition] = useState<QueryGoodsTableDataCondition<QueryMarketsGoodsResponse>>()
    const [loading, setLoading] = useState(false)
    useEffect(() => {
        let pageable = condition?.pagination ? mergePaginationAndPageable(condition.pagination, new Pageable(), condition.sorter) : new Pageable();
        setPageable(pageable)
        setLoading(true)
        queryMarketsGoods(id, pageable, condition ?? {}).then(response => {
            setData(response.data.content)
            setTotalElements(response.data.totalElements)
        }).finally(() => {
            setLoading(false)
        })
    }, [condition]);
    let factoriesLoader = useCallback(() => getMarketGoodsFactories(id), []);
    let brandLoader = useCallback(() => getMarketGoodsBrands(id), []);
    let categoryLoader = useCallback(() => getMarketGoodsCategories(id), []);
    return <>
        <DataPageLayout leftActions={<>
            <LoadableButton onClick={async () => {
                let response = await exportMarketsGoodsToExcel(id, condition ?? {});
                saveTo(response.data, `${name ?? ""}商品资料.xlsx`)
            }}>导出</LoadableButton>
        </>} rightActions={[]}>
            <OnlinePaginationGoodsTable<QueryMarketsGoodsResponse> data={data}
                                                                   customColumns={columns => {
                                                                       ArrayUtils.insertAfter(columns, value => value.dataIndex === "name", {
                                                                           dataIndex: "amountInMarket",
                                                                           title: "数量",
                                                                       })
                                                                       return columns
                                                                   }}
                                                                   factoriesLoader={factoriesLoader}
                                                                   categoriesLoader={categoryLoader}
                                                                   brandsLoader={brandLoader}
                                                                   pagination={{
                                                                       current: pageable.page,
                                                                       pageSize: pageable.size,
                                                                       total: totalElements,
                                                                   }}
                                                                   loading={loading}
                                                                   onConditionChange={(condition) => setCondition(condition)}/>
        </DataPageLayout>
        {employeeAuthorizationStore.hasAuthority("卖场_内部码_查询") && <><Divider>内部码管理</Divider>
            <MarketInternalGoodsCodeManager marketId={id}/></>}
    </>
}

const MarketOrdersTabPage: React.FC<{ id: number }> = ({id}) => {
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryMarketOrderResponse[]>([])
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)
    const [employeeIds, setEmployeeIds] = useState<number[]>([])

    const [openAddDrawer, setOpenAddDrawer] = useState(false)

    const [startDate, setStartDate] = useState<string>()
    const [endDate, setEndDate] = useState<string>()
    const [status, setStatus] = useState<MarketOrderStatus>()
    const query = useCallback(() => {
        setLoading(true)
        queryMarketOrders({
            marketIds: [id],
            employeeIds,
            startDate: startDate ? LocalDate.parse(startDate).toString() : undefined,
            endDate: endDate ? LocalDate.parse(endDate).toString() : undefined,
            status,
        }, pageable).then(response => {
            setData(response.data.content)
            setTotalElements(response.data.totalElements)
        }).finally(() => {
            setLoading(false)
        })
    }, [...pageable.toDependencyList(), id, employeeIds, startDate, endDate, status])
    useEffect(() => {
        query()
    }, [query]);
    const [createdByEmployees, setCreatedByEmployees] = useState<NumberIdAndName[]>([])
    useEffect(() => {
        getMarketOrderCreatedEmployeeByMarketId(id).then(response => response.data).then(setCreatedByEmployees)
    }, []);

    let navigate = useNavigate();
    let globalStyle = useGlobalStyle();
    return <>
        <DataPageLayout leftActions={[]} rightActions={<>
            {employeeAuthorizationStore.hasAuthority("卖场_订单_下单") && <LoadableButton onClick={async () => {
                let response = await createMarketOrder(id);
                navigate(`/markets/orders/${response.data}`)
            }}>下单</LoadableButton>}
        </>}>
            <Table<QueryMarketOrderResponse> className={globalStyle.rowClickableTable} onRow={item => {
                return {
                    onClick: () => {
                        navigate(`/markets/orders/${item.id}`)
                    }
                }
            }} size={"small"} loading={loading} dataSource={data} rowKey={"id"} pagination={{
                current: pageable.page,
                pageSize: pageable.size,
                total: totalElements,
            }} onChange={(pagination, filters, sorter) => {
                setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
                setEmployeeIds(filters["createdBy.name"] as number[])
                let filter = filters["status"] as unknown as MarketOrderStatus[];
                setStatus(filter ? filter[0] : undefined)
            }}>
                <Table.Column dataIndex={"createdDateTime"} title={"下单时间"}
                              {...useTableFilterDateRangeColumnProps<QueryMarketOrderResponse>("createdDateTime", {
                                  handleSearch: value => {
                                      setStartDate(value ? value[0].format() : undefined)
                                      setEndDate(value ? value[1].format() : undefined)
                                  }
                              })}
                              render={(value) => value.format(DATE_WITH_TIME_FORMATER)}/>
                <Table.Column dataIndex={["goodsKindAmount"]} title={"单品数量"}/>
                <Table.Column<QueryMarketOrderResponse> dataIndex={"status"}
                                                        filteredValue={status ? [status] : []}
                                                        title={"状态"}
                                                        key={"status"}
                                                        filterMultiple={false}
                                                        filters={marketOrderStatuses.map(it => ({
                                                            text: marketOrderStatusMap[it],
                                                            value: it
                                                        }))} render={(value, record) => {
                    return value === "DELIVERY" ? <Link onClick={event => event.stopPropagation()}

                                                        to={`/markets/deliveryOrders/${record.id}`}>已开送货单</Link> : marketOrderStatusMap[value]
                }}/>
                <Table.Column dataIndex={["createdBy", "name"]} title={"下单人员"}
                              filters={createdByEmployees.map(it => ({text: it.name, value: it.id}))}/>
                <Table.Column<QueryMarketOrderResponse> title={"操作"} render={(_, record) => {
                    return <>
                        {employeeAuthorizationStore.hasAuthority("卖场_订单_删除") && record.status === "WAIT_SUBMIT" &&
                            <LoadableButton type={"text"} danger onClick={async (event) => {
                                event.stopPropagation()
                                await deleteMarketOrder(record.id)
                                query()
                            }}><DeleteOutlined/>删除</LoadableButton>}
                    </>
                }}/>
            </Table>
        </DataPageLayout>
    </>
}

function MarketInventoryTabPage({id}: { id: number }) {
    const [pageable, setPageable] = useState(new Pageable())
    const [data, setData] = useState<QueryMarketCheckInventoryRecordResponse[]>([])
    const [loading, setLoading] = useState(false)
    const [totalElements, setTotalElements] = useState(0)
    const [employeeIds, setEmployeeIds] = useState<number[]>([])


    const [startDate, setStartDate] = useState<string>()
    const [endDate, setEndDate] = useState<string>()
    const [submitted, setSubmitted] = useState<boolean>()
    const query = useCallback(() => {
        setLoading(true)
        queryMarketCheckInventoryRecords({
            employeeIds,
            startDate: startDate ? LocalDate.parse(startDate).format(YEAR_MONTH_DAY_FORMATER) : undefined,
            endDate: endDate ? LocalDate.parse(endDate).format(YEAR_MONTH_DAY_FORMATER) : undefined,
            submitted,
            marketIds: [id],
        }, pageable).then(response => {
            setData(response.data.content)
            setTotalElements(response.data.totalElements)
        }).finally(() => {
            setLoading(false)
        })
    }, [...pageable.toDependencyList(), employeeIds, startDate, endDate, submitted, id])
    useEffect(() => {
        query()
    }, [query]);
    const [createdByEmployees, setCreatedByEmployees] = useState<NumberIdAndName[]>([])
    useEffect(() => {
        getCheckInventoryRecordCreatedEmployeesByMarketId(id).then(response => response.data).then(setCreatedByEmployees)
    }, []);


    let navigate = useNavigate();

    let globalStyle = useGlobalStyle();
    return <>
        <Table<QueryMarketCheckInventoryRecordResponse>
            className={`${globalStyle.rowClickableTable}`} onRow={item => {
            return {
                onClick: () => {
                    navigate(`/markets/checkInventoryRecords/${item.id}`)
                }
            }
        }} size={"small"} loading={loading} dataSource={data} rowKey={"id"} pagination={{
            current: pageable.page,
            pageSize: pageable.size,
            total: totalElements,
        }} onChange={(pagination, filters, sorter) => {
            setPageable(mergePaginationAndPageable(pagination, pageable, sorter))
            setEmployeeIds(filters["createdBy.name"] as number[])
            let filter = filters["submittedDateTime"] as unknown as boolean[];
            setSubmitted(filter ? filter[0] : undefined)
        }}>
            <Table.Column dataIndex={"name"} title={"名称"}/>
            <Table.Column dataIndex={["goodsKindAmount"]} title={"单品数量"}/>
            <Table.Column dataIndex={"createdDateTime"} title={"创建时间"}
                          {...useTableFilterDateRangeColumnProps<QueryMarketCheckInventoryRecordResponse>("createdDateTime", {
                              handleSearch: value => {
                                  setStartDate(value ? value[0].format() : undefined)
                                  setEndDate(value ? value[1].format() : undefined)
                              }
                          })}
                          render={(value) => LocalDate.parse(value).format(YEAR_MONTH_DAY_FORMATER)}/>
            <Table.Column<QueryMarketCheckInventoryRecordResponse> dataIndex={"submittedDateTime"}
                                                                   filteredValue={submitted ? [submitted] : []}
                                                                   title={"提交时间"}
                                                                   key={"status"}
                                                                   filterMultiple={false}
                                                                   filters={[{
                                                                       text: "已提交",
                                                                       value: true
                                                                   }, {
                                                                       text: "待提交",
                                                                       value: false
                                                                   }]}
                                                                   render={(value) => LocalDate.parse(value).format(YEAR_MONTH_DAY_FORMATER)}/>
            <Table.Column dataIndex={["createdBy", "name"]} title={"创建人"}
                          filters={createdByEmployees.map(it => ({text: it.name, value: it.id}))}/>
        </Table>
    </>;
}


